function hasData(item, field) {
  if (Array.isArray(item)) {
    return item.some(hasData)
  }
  if (item.type === 'surface') {
    return true
  }
  if (item.type === 'map' || item.type === 'map3D') {
    return item.map && !!window.echarts.getMap(item.map)
  }
  if (field && item[field] && item[field].length) {
    return true
  }
  return (item.data && item.data.length) || (item.nodes && item.nodes.length)
}

const waitTokens = {}

export default {
  isEmpty(options) {
    if (!options) {
      return true
    }

    if (options.xAxis) {
      if (hasData(options.xAxis)) {
        return false
      }
    }
    if (options.yAxis) {
      if (hasData(options.yAxis)) {
        return false
      }
    }
    if (options.singleAxis) {
      if (hasData(options.singleAxis)) {
        return false
      }
    }
    if (options.xAxis3D) {
      if (hasData(options.xAxis3D)) {
        return false
      }
    }
    if (options.yAxis3D) {
      if (hasData(options.yAxis3D)) {
        return false
      }
    }
    if (options.zAxis3D) {
      if (hasData(options.zAxis3D)) {
        return false
      }
    }

    if (options.series) {
      if (hasData(options.series)) {
        return false
      }
    }

    if (options.geo) {
      if (options.geo.some(g => g.map && window.echarts.getMap(g.map))) {
        return false
      }
    }

    if (options.geo3D) {
      if (options.geo3D.some(g => g.map && window.echarts.getMap(g.map))) {
        return false
      }
    }

    if (options.globe) {
      return false
    }

    if (options.radar) {
      if (hasData(options.radar, 'indicator')) {
        return false
      }
    }

    if (options.timeline) {
      if (hasData(options.timeline)) {
        return false
      }
    }

    if (options.graphic) {
      if (hasData(options.graphic, 'elements')) {
        return false
      }
    }

    if (options.calendar) {
      return false
    }

    return true
  },

  /**
   * 获取组件元素的大小
   * @param {Vue} component ECharts 组件实例
   */
  getSize(component) {
    const size = {
      width: 0,
      height: 0,
      isEmpty: true
    }

    if (!component.$el) {
      return size
    }

    const rect = component.$el.getClientRects()[0]
    if (!rect) {
      return size
    }
    size.width = Math.round(rect.width)
    size.height = Math.round(rect.height)
    size.isEmpty = false
    return size
  },
  async wait(timeout, token) {
    return new Promise((resolve, reject) => {
      const timer = setTimeout(() => {
        resolve()
      }, timeout)
      if (!token) {
        return
      }
      waitTokens[token] = {
        timer, reject
      }
    })
  },
  cancelWait(token) {
    if (!waitTokens[token]) {
      return
    }
    const {timer, reject} = waitTokens[token]

    delete waitTokens[token]

    clearTimeout(timer)
    reject(new Error('canceled'))
  },
  loadLibrary() {
    return import('echarts')
  }
}
